import requests
import time
import os
import logging
import threading
import inspect
from logging.handlers import RotatingFileHandler

handlers = {
            logging.DEBUG: './http.log',
            logging.INFO: './ping.log'
            }
logLevels = handlers.keys()
for level in logLevels:
    path = os.path.abspath(handlers[level])
    handlers[level] = RotatingFileHandler(path, maxBytes=9000000000, backupCount=2, encoding='utf-8')


class TNLog(object):

    def printfNow(self):
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

    def __init__(self, level=logging.NOTSET):
        self.__loggers = {}
        logLevels = handlers.keys()
        for level in logLevels:
            logger = logging.getLogger(str(level))
            # 如果不指定level，获得的handler似乎是同一个handler?
            logger.addHandler(handlers[level])
            logger.setLevel(level)
            self.__loggers.update({level: logger})

    def getLogMessage(self, level, message):
        frame, filename, lineNo, functionName, code, unknowField = inspect.stack()[2]
        '''日志格式：[时间] [类型]  信息'''
        return "[%s] [%s] %s" % (self.printfNow(), level, message)

    def info(self, message):
        message = self.getLogMessage("info", message)
        self.__loggers[logging.INFO].info(message)

    def debug(self, message):
        message = self.getLogMessage("debug", message)
        self.__loggers[logging.DEBUG].debug(message)


logger = TNLog()


# 检查系统是否还存活 true 还存活， false 已经关闭
def checkWeb(checkUrl):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0'}
        response = requests.get(url=checkUrl, timeout=2, headers=headers)  # 请求超时时间为2秒
        code = response.status_code  # http请求的返回状态，若为200则表示请求成功,返回的状态码是 int类型
        if code == 200:
            return True
        else:
            return False
    except:
        return False


# 主函数
def send():
    logger.debug('请求结果：' + str(checkWeb('http://192.168.1.108:8080/get.html')))


def pingAdd():
    res = os.popen('ping -n 1 192.168.1.108')
    logger.info(res.read().splitlines(keepends=False)[2])


def request():
    try:
        do = threading.Thread(target=send, )
        do.start()
        while do.is_alive():
            time.sleep(0.5)
    except Exception as r:
        print(str(r))
    finally:
        threading.Timer(1, request, ()).start()


def ping():
    try:
        do = threading.Thread(target=pingAdd, )
        do.start()
        while do.is_alive():
            time.sleep(0.5)
    except Exception as r:
        print(str(r))
    finally:
        threading.Timer(1, ping, ()).start()


request()
ping()